<template>
  <div class="deal-record-content">

    <header>
      <div class="black-bg"></div>
      <!--<div class="card-div">-->
      <div class="card">
        <img :src="backgroundImage" alt="">
      </div>
      <!--</div>-->
      <div class="mask" v-on:click="getCard" v-show="headMaskShow">
      </div>
      <div class="text" v-if="oneCardTextShow">
        <p>会员卡号</p>
        <p style="font-size: .533rem">{{bgImageText}}</p>
      </div>
      <div class="no-card-text" style="text-align: center" v-else>
        <p v-show="bgImageTextShow">{{bgImageText}}</p>
        <p v-show="bgImageTextShowToGetCard" v-on:click="getCard">{{bgImageText}}</p>
        <p v-show="bgImageTextShowByNoCard" v-on:click="getPay">{{bgImageText}}</p>
      </div>
    </header>

    <section style="text-align: center;line-height: 1.066rem;color: blue; height: 1.066rem;">
      <p v-show="switchCard" v-on:click="selectCard"><span> >> </span>切换会员卡</p>

      <select @change="selectedChange">
        <option v-for="item in cardList">{{item.card_no}}</option>
      </select>
    </section>

    <div class="weui-cells">

      <a class="weui-cell weui-cell_access" href="javascript:;" v-if="redirect" v-on:click="commonFunc(getBalance, needFirstPay)">
        <div class="weui-cell__bd">
          <p class="coin">我的储值</p>
        </div>
        <div class="weui-cell__ft">
          {{balance}}
        </div>
      </a>

      <a class="weui-cell weui-cell_access" href="javascript:;" v-else>
        <div class="weui-cell__bd">
          <p class="coin">我的储值</p>
        </div>
        <div class="weui-cell__ft">
          {{balance}}
        </div>
      </a>


      <div class="weui-cell">
        <div class="weui-cell__bd">
          <p class="score">我的积分</p>
        </div>
        <div class="weui-cell__ft" style="margin-right: .347rem;">{{point}}</div>
      </div>
      <a class="weui-cell weui-cell_access" href="javascript:;" v-on:click="commonFunc(tickets)">
        <div class="weui-cell__bd">
          <p class="ticket">我的优惠券</p>
        </div>
        <div class="weui-cell__ft">
          {{couponCount}}
        </div>
      </a>
      <a class="weui-cell weui-cell_access" href="javascript:;" v-on:click="commonFunc(getQrCodeStr)">
        <div class="weui-cell__bd">
          <p class="qrcode">我的二维码</p>
        </div>
        <div class="weui-cell__ft">
        </div>
      </a>
    </div>

    <div class="weui-cells" style="margin-top: .533rem">
      <a class="weui-cell weui-cell_access" href="javascript:;" v-on:click="commonFunc(dealRecord)">
        <div class="weui-cell__bd">
          <p class="deal-record">我的交易流水</p>
        </div>
        <div class="weui-cell__ft">
        </div>
      </a>
      <a class="weui-cell weui-cell_access" href="javascript:;" v-on:click="commonFunc(mbInfo)">
        <div class="weui-cell__bd">
          <p class="my">我的资料</p>
        </div>
        <div class="weui-cell__ft">
        </div>
      </a>
      <a class="weui-cell weui-cell_access" href="javascript:;" v-on:click="commonFunc(memberCardInfo)">
        <div class="weui-cell__bd">
          <p class="card-info">会员卡详情</p>
        </div>
        <div class="weui-cell__ft">
        </div>
      </a>
    </div>

    <div class="weui-cells" style="width: 90%; margin: 1.066rem auto" v-show="showBtn"
         v-on:click="getCard">
      <a href="javascript:;" class="weui-btn weui-btn_primary"
         style="height: 1rem;line-height: 1rem;font-size: .367rem">放入微信卡包</a>
    </div>

    <!--<div class="weui-cells" style="width: 90%; margin: 1.066rem auto" v-else v-show="showBtn">-->
    <!--<a href="javascript:;" class="weui-btn weui-btn_primary"-->
    <!--style="height: 1rem;line-height: 1rem;font-size: .367rem">放入微信卡包</a>-->
    <!--</div>-->

    <div id="dialog1" v-show="showQrcode">
      <div class="weui-mask"></div>
      <div class="weui-dialog weui-skin_android">
        <div class="weui-dialog__hd"><strong class="weui-dialog__title"
                                             style="font-size: .54rem;color: #333">{{alertTitle}}</strong></div>
        <div class="weui-dialog__bd" style="font-size: .427rem; color: #666">
          {{alertText}}
          <qrcode :value="qrCode" style="text-align: center;margin-top: 1.066667rem;"></qrcode>
        </div>
        <div class="weui-dialog__ft" v-show="showAlertFoot">
          <!--<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default" v-on:click="cancelAlert">取消</a>-->
          <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" v-on:click="cancelAlert"
             style="color: #ff6600">{{alertBtn}}</a>
        </div>

        <p style="text-align: center;background: #eee;height: 1.066667rem;border-top: 0.02667rem solid #dfdfdf;line-height: 1.066667rem;">
          到店出示给收银员即可使用
        </p>

        <div class="cancel-qrcode">
          <i class="fa fa-arrow-left" v-on:click="closeQrcodeDiv" style="font-size: 1.066667rem;padding: 0.2667rem;"></i>
        </div>

      </div>
    </div>


    <div id="dialog2" v-show="showAlert">
      <div class="weui-mask"></div>
      <div class="weui-dialog weui-skin_android">
        <div class="weui-dialog__hd"><strong class="weui-dialog__title" style="font-size: 0.533333rem;color: #333">提示</strong>
        </div>
        <div class="weui-dialog__bd" style="font-size: 0.426667rem; color: #666">{{alertText}}</div>
        <div class="weui-dialog__ft">
          <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" style="color: #ff6600"
             v-on:click="hideAlert">我知道了</a>
        </div>
      </div>
    </div>

    <loading :show="showLoading" :text="showLoadingText"></loading>
    <toast v-model="showToast" width="5rem" :type="toastType" :time="800" :text="toastText"></toast>

  </div>
</template>

<script>
  import {Loading, Toast, Qrcode} from 'vux'
  import 'font-awesome/css/font-awesome.css'
  import {utils} from './../common/utils/utils'
  import {oauth} from './../common/utils/oauth'
  import {wechat} from './../common/utils/wechat'

  const common = require('./../common/utils/common')

  async function showView(result, _this) {

    if (!common.isEmptyString(result)) {
      _this.showLoading = false

      const centerInfo = result["info"]

      _this.cardNo = result['info']['current_card_no']
      _this.backgroundImage = result['info']['current_card_backend_image']
      _this.posCode = result['info']['pos_code']
      _this.point = centerInfo.point
      _this.balance = (centerInfo.balance / 100).toFixed(2)
      _this.couponCount = centerInfo.coupon_count
      _this.needGetCard = centerInfo.need_get_card
      _this.backgroundImage = centerInfo.current_card_backend_image
      _this.cardList = result["card_list"]

      if (result['info']['card_issue'] == -1) {

        _this.bgImageTextShow = true
        _this.bgImageText = '该商户未设置自助领卡，请到柜台办理'
        _this.redirect = false

      } else {

        if (result['info']['card_issue'] == -2
          && result['info']['current_card_status'] == 2) {

          if (common.isEmptyString(result['info']['current_card_no'])) {
            _this.bgImageTextShowToGetCard = true
            _this.bgImageText = '您尚未领取会员卡，点击领取'

            _this.cardId = result['info']["card_id"]
            _this.cardExt = result['info']["card_ext"]

            wx.addCard({
              cardList: [{
                cardId: _this.cardId,
                cardExt: _this.cardExt
              }], // 需要添加的卡券列表
              success: async function (res) {

                const addResult = await utils.addWechatMemberCard(_this)

                if(addResult) {
                  location.reload()
                }

              },
              cancel: function (res) {
                _this.$router.push({
                  path: 'center',
                  params: ''
                })
              },
              fail: function (res) {
                _this.$router.push({
                  path: 'center',
                  params: ''
                })
              }
            });

          } else {
            _this.$router.push({
              name: 'Balance',
              params: {
                cardNo: result['info']['current_card_no']
              }
            })
          }

        } else if (result['info']['card_issue'] > 0
          && result['info']['current_card_status'] == 2) {

          if (common.isEmptyString(result['info']['current_card_no'])) {
            _this.bgImageTextShowToGetCard = true
            _this.bgImageText = '您尚未领取会员卡，点击领取'

            _this.cardId = result['info']["card_id"]
            _this.cardExt = result['info']["card_ext"]

            wx.addCard({
              cardList: [{
                cardId: _this.cardId,
                cardExt: _this.cardExt
              }], // 需要添加的卡券列表
              success: async function (res) {

                const addResult = await utils.addWechatMemberCard(_this)

                if(addResult) {
                  location.reload()
                }

              },
              cancel: function (res) {
                _this.$router.push({
                  path: 'center',
                  params: ''
                })
              },
              fail: function (res) {
                _this.$router.push({
                  path: 'center',
                  params: ''
                })
              }
            });

          } else {
            _this.orderNo = result['info']['order_no']
            _this.addLimit = result['info']['card_issue']

            _this.baseInfoClick = true

            _this.needFirstPay = true

            _this.bgImageTextShowToGetCard = false
            _this.bgImageTextShowByNoCard = true
            _this.bgImageText = '该商户需要购买会员卡，点击购买'

            const res = await utils.getPayBuyCard(_this)

            const webPayData = JSON.parse(res.data.web_pay_data)

            wechat.callPay(webPayData, _this)
          }

        } else {

          //没有卡，需要领取卡
          if (centerInfo.need_get_card) {
            _this.bgImageTextShowToGetCard = true
            _this.bgImageText = '你尚未领取会员卡，点击领取'

            _this.cardId = result['info']["card_id"]
            _this.cardExt = result['info']["card_ext"]

            wx.addCard({
              cardList: [{
                cardId: _this.cardId,
                cardExt: _this.cardExt
              }], // 需要添加的卡券列表
              success: async function (res) {

                const addResult = await utils.addWechatMemberCard(_this)

                if(addResult) {
                  location.reload()
                }

              },
              cancel: function (res) {
                _this.$router.push({
                  path: 'center',
                  params: ''
                })
              },
              fail: function (res) {
                _this.$router.push({
                  path: 'center',
                  params: ''
                })
              }
            });

            return false
          }
          //是否显示按钮
          if (!centerInfo.access_wx_card) {
            _this.showBtn = true
          }

          //只有一张卡的情况下
          if (_this.cardList.length === 1) {
            _this.headMaskShow = false
            _this.oneCardTextShow = true
            _this.oneCardShowTip = true
            _this.bgImageText = centerInfo.current_card_no
          } else if (_this.cardList.length > 1) {
            _this.headMaskShow = false
            _this.bgImageText = _this.selectedCardNo ? _this.selectedCardNo : _this.cardNo = centerInfo.current_card_no
            _this.oneCardTextShow = true
            _this.switchCard = true
          }

        }
      }
    }

  }

  export default {
    components: {
      Loading,
      Toast,
      Qrcode
    },
    name: 'hello',
    data() {
      return {
        mchCodeByUrl: common.getUrlParam('mchCode'),
        openidByUrl: common.getUrlParam('openid'),
        payOpenidByUrl: common.getUrlParam('payOpenid'),
        cacheMchCode: localStorage.getItem('mchCode'),
        cacheMchType: localStorage.getItem('type'),
        openid: localStorage.getItem('openid'),
        payOpenid: '',

        qrCode: '',

        //当前页数据
        backgroundImage: '',
        balance: '0.00',
        point: '0',
        couponCount: '0',
        cardExt: '',
        cardId: '',
        cardNo: '',
        cardList: [],
        needGetCard: false,
        needFirstPay: false,
        cardIsSue: 0,
        orderNo: '',
        posCode: '',

        centerInfo: [],

        selectedCardNo: '',

        oneCardTextShow: false,
        oneCardShowTip: false,
        bgImageTextShow: false,
        bgImageTextShowByNoCard: false,
        bgImageTextShowToGetCard: false,
        bgImageText: '你尚未领取会员卡，点击领取',
        redirect: true,
        headMaskShow: true,

        showBtn: false,
        switchCard: false,

        showAlert: false,
        showQrcode: false,
        alertText: '该手机号已注册，请直接绑定会员',
        alertBtn: '',
        alertTitle: '提示',
        showAlertFoot: true,

        showMask: false,
        showLoading: false,
        showLoadingText: '',
        showToast: false,
        toastType: 'cancel',
        toastText: '',

        fetchIntoWxFunc: function () {
          console.log('我的卡包')
        },

        baseInfoClick: false

      }
    },
    beforeCreate() {
      document.title = '会员中心'
    },
    async created() {

      this.showLoading = true

      this.selectedCardNo = this.$route.params.selectedCardNo
      const _this = this

      //授权
      oauth.checkOauth(utils, _this)

      const payOpenidByUrl = common.getUrlParam('payOpenid')

      if(common.isEmptyString(localStorage.getItem('payOpenid'))) {

        if(common.isEmptyString(payOpenidByUrl)) {
          //获取支付openid
          const payOpenid = await utils.getPayOauth(_this)
          localStorage.setItem('payOpenid', payOpenid)
          this.payOpenid = payOpenidByUrl
        } else {
          localStorage.setItem('payOpenid', payOpenidByUrl)
          this.payOpenid = payOpenidByUrl
        }

      } else {
        this.payOpenid = localStorage.getItem('payOpenid')
      }

      const result = await utils.center(_this)

      await showView(result, _this)

    },
    methods: {

      commonFunc: function (targetFunc, needFirstPay=false) {

        window.scrollTo(0, 0)

        if (this.needGetCard) {
          this.getCard()
          return false
        }

        if (needFirstPay) {
          utils.getPayBuyCard(this)
          return false
        }

        targetFunc()

      },

      selectCard: function () {
        this.switchCard = true
      },

      selectedChange: async function (ele) {

        this.showLoading = true
        const _this = this;
        _this.cardNo = ele.target.value
        const result = await utils.center(_this)

        await showView(result, _this);

      },

      cancelAlert: function () {
        this.showAlert = false
      },

      //获取微信卡包
      getCard: function () {
        const _this = this

        wx.addCard({
          cardList: [{
            cardId: this.cardId,
            cardExt: this.cardExt
          }], // 需要添加的卡券列表
          success: async function (res) {

            const addResult = await utils.addWechatMemberCard(_this)

            if(addResult) {
              location.reload()
            }

          },
          cancel: function (res) {
            _this.$router.push({
              path: 'center',
              params: ''
            })
          },
          fail: function (res) {
            _this.$router.push({
              path: 'center',
              params: ''
            })
          }
        });
      },

      memberCardInfo: function () {
        this.$router.push({
          name: 'MemberCard',
          params: {'cardNo': this.cardNo}
        })
      },

      getBalance: function () {

        const params = {
          cardNo: this.cardNo
        }

        if (!common.isEmptyString(this.selectedCardNo)) {
          params["cardNo"] = this.selectedCardNo
        }

        this.$router.push({
          name: 'Balance',
          params: params
        })

      },

      mbInfo: function () {
        this.$router.push({
          path: 'my',
          params: ''
        })
      },

      dealRecord: function () {
        this.$router.push({
          path: 'dealRecord',
          params: ''
        })
      },

      tickets: function () {
        this.$router.push({
          path: 'tickets',
          params: ''
        })
      },

      getQrCodeStr: async function () {
        this.showQrcode = true
        this.alertText = ''
        this.alertBtn = ''
        this.alertTitle = ''
        this.showAlertFoot = false

        const _this = this

        const result = await utils.myQrcode(_this)

        if (result.code === 200) {
          this.qrCode = result.values.qrcode
        }
      },

      hideAlert: function () {
        this.showAlert = false
      },

      closeQrcodeDiv: function () {
        this.showQrcode = false
      },

      getPay: async function () {
        const _this = this
        const res = await utils.getPay(_this)

        const webPayData = JSON.parse(res.data.web_pay_data)

        wechat.callPay(webPayData, _this)
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .weui-cells {
    margin-top: 0;
  }

  .deal-record-content {
    background-color: #f2f2f2;
    min-height: 17.787rem;
  }

  .coin, .ticket, .score, .qrcode, .deal-record, .my, .card-info {
    padding-left: 1.066rem;
    font-size: .373rem;
  }

  .coin {
    background: url("./../assets/image/coin.png") no-repeat 0 0;
  }

  .ticket {
    background: url("./../assets/image/ticket.png") no-repeat 0 0;
  }

  .qrcode {
    background: url("./../assets/image/qrcode.png") no-repeat 0 0;
  }

  .score {
    background: url("./../assets/image/score.png") no-repeat 0 0;
  }

  .deal-record {
    background: url("./../assets/image/deal-record.png") no-repeat 0 0;
  }

  .my {
    background: url("./../assets/image/avator.png") no-repeat 0 0;
  }

  .card-info {
    background: url("./../assets/image/member-card.png") no-repeat 0 0;
  }

  header {
    height: 5.653rem;
    /*position: relative;*/
  }

  .black-bg {
    height: 3.2rem;
    width: 100%;
    background-color: #000;
  }

  .card {
    position: absolute;
    left: 8.53%;
    top: 0.533rem;
    height: 5.12rem;
    width: 8.187rem;
    z-index: 2;
  }

  .card img {
    width: 100%;
  }

  .mask {
    position: relative;
    height: 5.2rem;
    width: 8.187rem;
    background-color: #000;
    left: 8.3%;
    margin-top: -2.707rem;
    opacity: .75;
    z-index: 3;
    border-radius: .133rem;
    border: .0267rem solid #fefefe;
  }

  .mask p {
    color: #fff;
    text-align: center;
    padding-top: 4.233rem;
    font-size: .373rem;
  }

  .text {
    position: absolute;
    margin-top: .866rem;
    color: #fff;
    z-index: 4;
    left: 1.066rem;
  }

  .no-card-text {
    margin-top: -0.933rem;
    color: #fff;
    z-index: 4;
    position: relative;
    text-align: center;
  }

  select {
    border: 0.02667rem solid red;
    z-index: 100;
    position: absolute;
    top: 5.866667rem;
    left: 4.0rem;
    opacity: 0
  }
</style>
